package com.jess.arms.cj;

import io.reactivex.Observable;
import io.reactivex.functions.Function;

/**
 * @Title: ApiOperator
 * @Package com.chinamall21.mobile.common.api
 * @Description: Api请求转换, 对请求过程进行封装, 简化请求处理过程
 * @author: 王力杨
 * @date: 16/5/24 上午10:01
 */
public class ApiOperator {
    private IRequestMapper mapper;

    public ApiOperator(IRequestMapper mapper) {
        this.mapper = mapper;
    }

    public final <T, P> Observable<P> chain(T t, final ApiAction<T, P> action) {
        return Observable.just(t)
                .flatMap(t1 -> action.chain(t1))
                .flatMap(this.<P>transformResponse());
    }

    /**
     * 服务其返回的数据解析
     * 正常服务器返回数据和服务器可能返回的exception
     *
     * @param <P>
     */
    public static final <P> Function<GsonResponse<P>, Observable<P>> transformResponse() {
        //转化成Observable<P>
        return pGsonResponse -> {
            if (pGsonResponse == null) {
                ApiException exp = new ApiException(ErrorCode.SERVER_ERROR, "服务器错误");
                return Observable.error(exp);
            } else {
                P data = pGsonResponse.getData();
                if (pGsonResponse.isFail()) {
                    return Observable.error(new ApiException(pGsonResponse.getCode(), pGsonResponse.getMessage()));
                } else {
                    // 若data为null，返回P类型的默认值（需确保默认值类型匹配）
                    if (data == null) {
                        // 若 P 是 CommonResponse，返回其空实例（需确保类型匹配）
                        data = (P) new CommonResponse(); // 或根据业务设置默认字段
                    }

                    return Observable.just(data);
                }
            }
        };
    }
}
